<template>
  <div>
    <common-menu :to-path="['blogPublish','blogList']" :text="['发布','列表']"></common-menu>
    <keep-alive>
      <router-view></router-view>
    </keep-alive>
    <div class="my-padded-tb-large">
      <div class="ui container">
        <div class="ui segment form">
          <el-form ref="blogForm" :model="blogForm">
            <el-form-item>
              <el-select v-model="blogForm.flag" style="width: 70px;">
                <el-option :label="'原创'" :value="0"></el-option>
                <el-option :label="'转载'" :value="1"></el-option>
                <el-option :label="'翻译'" :value="2"></el-option>
                <el-option :label="'其他'" :value="3"></el-option>
              </el-select>
              <el-input v-model="blogForm.title" style="width: 1027px;" placeholder="标题"></el-input>
            </el-form-item>
            <el-form-item>
              <mavon-editor v-model="blogForm.content" @imgAdd="imgAdd" @imgDel="imgDel" class="my-editor"/>
            </el-form-item>
            <el-form-item>
              <el-tag effect="plain" style="height: 39px;line-height: 39px">分类</el-tag>
              <el-select v-model="blogForm.typeId" placeholder="请选择分类" style="width: 500px;">
                <el-option v-for="item in types" :key="item.name" :label="item.name" :value="item.id"></el-option>
              </el-select>
              <el-tag effect="plain" style="height: 39px;line-height: 39px;margin-left: 5px;">标签</el-tag>
              <el-select v-model="blogForm.tagIds" multiple allow-create default-first-option placeholder="请选择标签" style="width: 500px;">
                <el-option v-for="item in tags" :key="item.name" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-tag effect="plain" style="height: 39px;line-height: 39px">首图</el-tag>
              <el-input v-model="blogForm.firstPicture" style="width: 1050px;" placeholder="首图地址"></el-input>
            </el-form-item>
            <el-form-item>
              <el-input type="textarea" :rows="6" placeholder="请输入博客简要描述" v-model="blogForm.description">
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-checkbox v-model="recommend">推荐</el-checkbox>
              <el-checkbox v-model="shareStatement">转载声明</el-checkbox>
              <el-checkbox v-model="appreciation">赞赏</el-checkbox>
              <el-checkbox v-model="commentabled">评论</el-checkbox>
            </el-form-item>
            <div class="ui right aligned container">
              <button type="button" class="ui button" onclick="window.history.go(-1)">返回</button>
              <button type="button" @click="saveBlog(1)" class="ui secondary button">保存</button>
              <button type="button" @click="saveBlog(0)" class="ui blue button">发布</button>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import BlogMenu from "../../components/CommonMenu";
  import CommonMenu from "../../components/CommonMenu";
  import {queryAllType} from "../../api/type";
  import {queryAllTag} from "../../api/tag";
  import {queryBlogById, saveBlog, updateBlog} from "../../api/blog";

  export default {
    name: "BlogPublish",
    components: {CommonMenu, BlogMenu},
    data() {
      return {
        blogForm: {
          title:'',
          content: '',
          firstPicture: '',
          flag: 0,
          recommend: 0,
          shareStatement: 1,
          appreciation: 1,
          commentabled: 1,
          typeId: null,
          tagIds: null,
        },
        // 是否推荐
        recommend: true,
        // 是否开启转载声明
        shareStatement: false,
        // 是否开启赞赏
        appreciation: false,
        // 是否开启评论
        commentabled: false,
        types: [],
        tags: [],
        img_file: [],
      }
    },
    created() {
    },
    activated() {
      this.getTags();
      this.getTypes();
      if (this.$route.params.blogId !== undefined) {
        queryBlogById(this.$route.params.blogId).then(res => {
          if (res.code === 200) {
            this.blogForm = res.data
            this.blogForm.flag = parseInt(this.blogForm.flag)
            this.recommend = this.blogForm.recommend == 0
            this.shareStatement= this.blogForm.shareStatement == 0
            this.appreciation= this.blogForm.appreciation == 0
            this.commentabled= this.blogForm.commentabled == 0
          }
        })
      }
      // 新增
      if (this.$route.params.flag === 1) {
        this.blogForm = {
          title:'',
          content: '',
          firstPicture: '',
          flag: 0,
          recommend: 0,
          shareStatement: 1,
          appreciation: 1,
          commentabled: 1,
          typeId: null,
          tagIds: null,
        }
        this.recommend = true
        this.shareStatement= false
        this.appreciation= false
        this.commentabled= false
      }
    },
    watch: {
      recommend: function (val, oldVal) {
        if (val) {
          this.blogForm.recommend = 0
        } else {
          this.blogForm.recommend = 1
        }
      },
      shareStatement: function (val, oldVal) {
        if (val) {
          this.blogForm.shareStatement = 0
        } else {
          this.blogForm.shareStatement = 1
        }
      },
      appreciation: function (val, oldVal) {
        if (val) {
          this.blogForm.appreciation = 0
        } else {
          this.blogForm.appreciation = 1
        }
      },
      commentabled: function (val, oldVal) {
        if (val) {
          this.blogForm.commentabled = 0
        } else {
          this.blogForm.commentabled = 1
        }
      },
    },
    methods: {
      imgAdd(pos, $file) {
        // 第一步.将图片上传到服务器.
        var formdata = new FormData();
        formdata.append('image', $file);
        this.img_file[pos] = $file;
        // this.$http({
        //   url: '/api/edit/uploadimg',
        //   method: 'post',
        //   data: formdata,
        //   headers: { 'Content-Type': 'multipart/form-data' },
        // }).then((res) => {
        //   let _res = res.data;
        //   // 第二步.将返回的url替换到文本原位置[外链图片转存失败(img-v2eG7egk-1562220599730)(0)] -> [外链图片转存失败(img-RmlJ1kIp-1562220599733)(url)]
        //   this.$refs.md.$img2Url(pos, _res.url);
        // })
      },
      imgDel(pos) {
        delete this.img_file[pos];
      },
      getTypes() {
        queryAllType().then(res => {
          if (res.code === 200) {
            this.types = res.data;
          }
        })
      },
      getTags() {
        queryAllTag().then(res => {
          if (res.code === 200) {
            this.tags = res.data;
          }
        })
      },
      // published 0发布 1保存
      // flag 0修改 1新增
      saveBlog(published) {
        let flag = this.$route.params.flag
        // 无输入
        if (this.blogForm.title===''||this.blogForm.content===''
          ||this.blogForm.firstPicture===''||this.blogForm.typeId==null
          ||this.blogForm.tagIds.length===0||this.blogForm.description==null) {
          this.$message({
            message: "请输入内容",
            type: 'error',
          })
          return
        }
        this.blogForm.published = published
        let page = this.$route.params.page
        const h = this.$createElement;
        this.$msgbox({
          title: '消息',
          message: h('p', null, [
            h('span', null, '确认' + (flag===0?'修改 ':'新增 ') + '标题为  '),
            h('strong', { style: 'color: teal' }, this.blogForm.title),
            h('span', null, ' 的博客吗 '),
          ]),
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              instance.confirmButtonLoading = true;
              instance.confirmButtonText = '执行中...';
              setTimeout(() => {
                done();
                setTimeout(() => {
                  instance.confirmButtonLoading = false;
                }, 300);
                // 0编辑 1新增
                if (flag===0) {
                  let updateForm = {
                    id: this.blogForm.id,
                    title: this.blogForm.title,
                    flag: this.blogForm.flag,
                    appreciation: this.blogForm.appreciation,
                    commentabled: this.blogForm.commentabled,
                    content: this.blogForm.content,
                    firstPicture: this.blogForm.firstPicture,
                    published: this.blogForm.published,
                    recommend: this.blogForm.recommend,
                    shareStatement: this.blogForm.shareStatement,
                    tagIds: this.blogForm.tagIds,
                    typeId: this.blogForm.typeId,
                    description: this.blogForm.description,
                  }
                  updateBlog(updateForm).then(res => {
                    if (res.code === 200) {
                      this.$message({
                        message: "更新成功",
                        type: 'success',
                      })
                    } else {
                      return Promise.reject('error');
                    }
                  })
                } else {
                  saveBlog(this.blogForm).then(res => {
                    if (res.code === 200) {
                      this.$message({
                        message: "添加成功",
                        type: 'success',
                      })
                    } else {
                      return Promise.reject('error');
                    }
                  })
                }
                setTimeout(() => {
                  if (flag === 0) {
                    this.$router.push({name: 'Blog',query:{flag:flag,page:page}})
                  } else {
                    this.$router.push({name: 'Blog',query:{flag:flag}})
                  }
                }, 1000)
              }, 3000);
            } else {
              done();
            }
          }
        });
      },
    }
  }
</script>

<style scoped>

</style>
